function UrlBuilder(baseUrl) {
  let first = true
  let url = baseUrl

  this.append = (key, value) => {
    if (typeof value == 'undefined' || value == '' || value == null) return this

    url = url + (first ? '?' : '&') + (`${key}=${value}`)
    if (first) first = false
    return this
  }

  this.url = () => url
}

export const nav2 = {
  navigate(url) {
    wx.navigateTo({
      url
    })
  },
  promotion() {
    this.navigate('/pages/promotion/promotion')
  },
  fastDelivery() {
    this.navigate('/pages/fast-delivery/fast-delivery')
  },
  chat(sessionOpenId, userId, from, autoMsg) {
    // autoMsg = { orderId, ticket, shopName } // send order msg
    // autoMsg = { goodsId, showTicket, title } // send goods msg
    const {
      orderId,
      ticket,
      shopName,
      goodsId,
      showTicket,
      title
    } = autoMsg || {}
    // console.log(sessionOpenId, userId, from, autoMsg)
    const url = new UrlBuilder('/pages/chat/chat')
      .append('sessionOpenId', sessionOpenId)
      .append('userId', userId).append('from', from)
      .append('orderId', orderId).append('ticket', ticket).append('shopName', shopName)
      .append('goodsId', goodsId).append('showTicket', showTicket).append('title', title)
      .url()
    this.navigate(url)
  },
  chatList() {
    this.navigate('/pages/chat/list/chatlist')
  },
  staffEdit(action, id) { // { action: 'new'|'edit'|'read', id } 
    this.navigate(`/pages/usercenter/staff/edit/index?action=${action}&id=${id}`)
  },
  staffList(action) { // select
    this.navigate(`/pages/usercenter/staff/index?action=${action}`)
  },
  personInfo() {
    this.navigate('/pages/usercenter/person-info/index')
  },
  /**
   * @param {*} action 'myOrder' | 'manage'
   * @param {*} ticket true | 'undefined', 进我的订单 or 我的水票 （action=='manage'时忽略)
   * @param {*} search {orderId, openId, refound, ticket, goodsId, dateRange}
   */
  orderList(action, ticket, search) {
    this.navigate(`/pages/order/order-list/index?action=${action}&search=${search}&ticket=${ticket}`)
  },
  goodsDetail(id, showTicket) {
    this.navigate(new UrlBuilder('/pages/goods/details/index')
      .append('id', id).append('showTicket', showTicket)
      .url())
  },
  goods(id, showTicket) {
    this.goodsDetail(id, showTicket)
  },
  developer() {
    this.navigate('/pages/usercenter/dev/dev')
  },
  deliveryFee(staffId, nickName) {
    nickName = nickName || '(无昵称)'
    wx.navigateTo({
      url: `/pages/usercenter/staff/deliveryFee/deliFee?staffId=${staffId}&nickName=${nickName}`,
    })
  },
  deductFee(staffId, nickName) {
    nickName = nickName || '(无昵称)'
    wx.navigateTo({
      url: `/pages/usercenter/staff/deductFee/deductFee?staffId=${staffId}&nickName=${nickName}`,
    })
  },
  pladge(staffId) {
    wx.navigateTo({
      url: '/pages/usercenter/pladge/pladge?action=manage&staffId=' + staffId,
    })
  }
}